<template>
    <view>
        <scroll-view @scroll="scroll" :scroll-top="scrollTop" :scroll-y="true" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0">
            <view class="container" v-if="detail.goods_id">
                <view class="swiper">
                    <swiper
                        :autoplay="autoplay"
                        @change="setCurrent"
                        class="banner-box swiper-box"
                        :duration="duration"
                        :indicator-dots="indicatorDots"
                        :interval="interval"
                        :circular="true"
                    >
                        <swiper-item @tap="previewImages" :data-index="index" v-for="(item, index) in detail.image" :key="index">
                            <image class="slide-image" mode="aspectFill" :src="item.file_path"></image>
                        </swiper-item>
                    </swiper>
                    <view class="sale-goods">
                        <view class="sale-goods-left">
                            <view class="sale-goods-prs-pic">
                                ￥
                                <strong>{{ goods_price }}</strong>
                            </view>
                            <view class="sale-goods-ori-pic">
                                <text class="text-name">限时抢购</text>
                                <text class="pic-text" v-if="line_price > 0">￥{{ line_price }}</text>
                            </view>
                        </view>
                        <view class="sale-goods-right">
                            <view class="sale-goods-title">距结束还剩</view>
                            <view class="sale-goods-time">
                                <view class="sale-goods-time-s">{{ clock }}</view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="cont-box b-f">
                    <view class="dis-flex flex-y-center">
                        <view class="left flex-box dis-flex flex-dir-column">
                            <view class="goods-title">
                                <text class="title f-32 twolist-hidden">{{ detail.goods_name }}</text>
                            </view>
                            <view class="money-box"></view>
                        </view>
                        <view class="right goods__share">
                            <form @submit="openActionsheet" :report-submit="true">
                                <button formType="submit" class="share-btn dis-flex flex-dir-column">
                                    <text class="share__icon iconfont icon-fenxiang"></text>
                                    <text class="f-24">分享</text>
                                </button>
                            </form>
                        </view>
                    </view>
                    <view class="goods-sales-box f-28 dis-flex">
                        <text class="flex-box num">销量：{{ detail.sales_sum + detail.salesinitial }}</text>
                        <text class="flex-box stock">库存：{{ stock_num }}</text>
                    </view>
                </view>
                <view @tap="onChangeShowState" class="cont-box b-f goods-property-box m-top20">
                    <text class="col-3 f-30">已选</text>
                    <text class="col-3 f-30 pl-12">{{ goods_num }} 个</text>
                    <view class="goods-property-jianTou">
                        <text :class="'iconfont icon-xiangyoujiantou user-orderJtou-1 ' + (showView ? 'user-orderJtou-2' : '')"></text>
                    </view>
                </view>
                <view :class="'cart v-hide ' + (showView ? 'v-show' : '')">
                    <view class="modal_cont_box">
                        <scroll-view class="goods-list-box" :scroll-y="true">
                            <view class="cf tmall-types" v-for="(attr, attr_idx) in specData" :key="attr_idx">
                                <view v-if="attr.spec_item.length > 0">
                                    <view class="tipstxt" :data-id="attr.group_id">{{ attr.name }}</view>
                                    <view class="cf cartypelist" v-for="(item, item_idx) in attr.spec_item" :key="item_idx">
                                        <view v-if="item.checked">
                                            <view @tap="modelTap" class="cartypeitem cur" :data-attr-idx="attr_idx" :data-item-idx="item_idx">{{ item.item }}</view>
                                        </view>

                                        <view v-else>
                                            <view @tap="modelTap" class="cartypeitem" :data-attr-idx="attr_idx" :data-item-idx="item_idx">{{ item.item }}</view>
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <view class="buy_number">
                                <view class="buyNumber f-26">
                                    <text>购买数量</text>
                                </view>
                                <view class="selectNumber">
                                    <button @tap="down" :class="'default  ' + (goods_num > 1 ? '' : ' default-active')" type="default">-</button>
                                    <input @input="importFun" type="number" :value="goods_num" disabled />
                                    <button @tap="up" class="default" type="default">+</button>
                                </view>
                            </view>
                        </scroll-view>
                    </view>
                </view>

                <!-- 商品评价 -->
                <view class="goods_comment" v-if="detail.comment_data.length">
                    <view class="cont-box b-f goods-property-box m-top20">
                        <text class="col-3 f-30">评价 ({{ detail.comment_data_count }}条)</text>
                        <text @tap="navigateToComment" class="comment-num">查看更多</text>
                        <view class="goods-property-jianTou">
                            <text class="iconfont icon-xiangyoujiantou user-orderJtou" style="margin-top: 0"></text>
                        </view>
                    </view>
                    <view class="goods_comment_box b-f" v-for="(item, index) in detail.comment_data" :key="index">
                        <view class="cont-box goods-comment-box b-t b-f b-b">
                            <view class="dis-flex">
                                <view class="user">
                                    <text class="user_name f-26">{{ item.user.nickName }}</text>
                                </view>
                                <view class="com_xing">
                                    <text class="iconfont icon-shoucang active"></text>
                                    <block v-if="item.score < 30">
                                        <text class="iconfont icon-shoucang active"></text>
                                        <text class="iconfont icon-shoucang active"></text>
                                    </block>
                                    <block v-if="item.score < 20">
                                        <text class="iconfont icon-shoucang active"></text>
                                        <text class="iconfont icon-shoucang active"></text>
                                    </block>
                                </view>
                            </view>
                            <view class="goods-comment-cont m-top20">
                                <text class="f-26 twolist-hidden">{{ item.content }}</text>
                            </view>
                            <view class="f-22 col-9 m-top10">{{ item.create_time }}</view>
                        </view>
                    </view>
                </view>

                <!-- 商品描述 -->
                <view class="p-bottom">
                    <view class="top-nav m-top20 b-f b-b">
                        <view class="top-nav-bar">
                            <view @tap="toOrder" id="top-nav-bar-true">
                                <span>商品描述</span>
                            </view>
                        </view>
                    </view>
                    <view class="order" v-if="!hiddenOrder">
                        <view v-if="detail.content != ''">
                            <view class="b-f goods-detail-box">
                                <view class="goods-cont-li">
                                    <!-- <template is="wxParse" :data="wxParseData:content.nodes"></template> -->
                                    <mp-html :content="article_content"></mp-html>
                                </view>
                            </view>
                        </view>
                        <view v-else>
                            <view class="yoshop-notcont">
                                <text class="iconfont icon-wushuju"></text>
                                <text class="cont">亲,此处暂无详情数据</text>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 底部操作栏 -->
                <view class="footer-fixed f-30">
                    <view class="goods-fixed-icon">
                        <contact-button sessionFrom="weapp" size="27" style="opacity: 0; position: absolute; top: 20rpx; left: 20rpx" type="default-light"></contact-button>
                        <image class="flow-img" src="/static/images/kefu.png"></image>
                    </view>
                    <view @tap="flowCart" class="goods-fixed-icon">
                        <image class="flow-img" src="/static/images/flow.png"></image>
                        <view class="flow_num" v-if="cart_total_num > 0">
                            <text>{{ cart_total_num }}</text>
                        </view>
                    </view>
                    <block v-if="stock_num > 0">
                        <view @tap="submit" class="order-bt" data-type="buyNow" data-prom="2">一键秒杀</view>
                    </block>
                    <view class="default-btn" style="wdata-typeth: 100%" v-else>已经截止</view>
                </view>
            </view>
        </scroll-view>

        <!-- 返回顶部 -->
        <view @tap="goTop" class="widget-goTop" v-if="floorstatus">
            <text class="iconfont icon-fanhuidingbu"></text>
        </view>

        <!-- 分享按钮 -->
        <zan-actionsheet
            :show="share.show"
            :actions="share.actions"
            :cancel-text="share.cancelText"
            :cancel-with-mask="share.cancelWithMask"
            @cancel="closeActionSheet"
            @actionclick="clickAction"
            mask-class="tiny"
        />

        <!-- 商品海报 弹出层 -->
        <zan-popup :show="share.showPopup" @close="togglePopup">
            <view class="pop-poster pop-example__container">
                <!-- 关闭按钮 -->
                <view class="pop-close dis-flex flex-x-center flex-y-center" @tap="togglePopup">
                    <text class="iconfont icon-shanchu f-30 col-9"></text>
                </view>
                <form @submit="savePoster" :report-submit="true">
                    <view class="poster__image">
                        <image mode="widthFix" :src="qrcode"></image>
                    </view>
                    <view class="poster__tips m-top10 t-c">
                        <text class="f-24 col-9">保存图片后，可分享到朋友圈</text>
                    </view>
                    <view class="padding-box m-top10 profile-btn">
                        <button formType="submit">保存图片</button>
                    </view>
                </form>
            </view>
        </zan-popup>
    </view>
</template>

<script>
import zanActionsheet from '@/pages/actionsheet/index';
import zanPopup from '@/pages/popup/index';
const app = getApp();
const wxParse = require('../../utils/wxParse.js');
var order = ['red', 'yellow', 'blue', 'green', 'red'];
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '/';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    var D = date.getDate() + ' ';
    var h = date.getHours() + 2 + ':0:0';
    return Y + M + D + h;
}

/* 毫秒级倒计时 */
function countdown(that, total_micro_second) {
    // 渲染倒计时时钟
    that.setData({
        clock: dateformat(total_micro_second)
    });
    if (total_micro_second <= 0) {
        total_micro_second = 0;
        that.setData({
            clock: '已经截止',
            stock_num: 0
        });
        // timeout则跳出递归
        return;
    }
    setTimeout(function () {
        // 放在最后--
        total_micro_second -= 10;
        countdown(that, total_micro_second);
    }, 10);
}

// 时间格式化输出，如3:25:19 86。每10ms都会调用一次
function dateformat(micro_second) {
    // 秒数
    var second = Math.floor(micro_second / 1000);
    // 小时位
    var hr = Math.floor(second / 3600);
    // 分钟位
    var min = Math.floor((second - hr * 3600) / 60);
    // 秒位
    var sec = second - hr * 3600 - min * 60; // equal to => var sec = second % 60;
    // 毫秒位，保留2位
    var micro_sec = Math.floor((micro_second % 1000) / 10);
    return hr + ':' + min + ':' + sec;
}
export default {
    components: {
        zanActionsheet,
        zanPopup
    },
    data() {
        return {
            indicatorDots: true,

            // 是否显示面板指示点
            autoplay: true,

            // 是否自动切换
            interval: 3000,

            // 自动切换时间间隔
            duration: 800,

            // 滑动动画时长

            currentIndex: 1,

            // 轮播图指针
            floorstatus: false,

            // 返回顶部
            showView: true,

            // 显示商品规格

            detail: {
                goods_id: '',
                image: [],
                goods_name: '',
                sales_sum: '',
                salesinitial: '',
                comment_data: [],
                comment_data_count: '',
                content: ''
            },

            // 商品详情信息
            goods_price: 0,

            // 商品价格
            stock_num: 0,

            // 库存数量

            goods_num: 1,

            // 商品数量
            item_sku_id: 0,

            // 规格id
            cart_total_num: 0,

            // 购物车商品总数量
            specData: {},

            // 多规格信息
            clock: '',

            // 分享按钮组件
            share: {
                show: false,
                cancelWithMask: true,
                cancelText: '关闭',
                actions: [
                    {
                        name: '生成商品海报',
                        className: 'action-class',
                        loading: false
                    },
                    {
                        name: '发送给朋友',
                        openType: 'share'
                    }
                ],
                // 商品海报
                showPopup: false
            },

            // 记录规格的数组
            goods_spec_arr: [],

            line_price: '',
            scrollTop: 0,
            attr_idx: 0,

            attr: {
                spec_item: [],
                group_id: '',
                name: ''
            },

            hiddenOrder: '',
            article_content: '',
            qrcode: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (e) {
        let that = this;
        let scene = app.globalData.getSceneData(e); // 商品id
        that.item_id = e.item_id ? e.item_id : scene.gid;
        // 获取商品信息
        that.getGoodsDetail();
        var date = new Date();
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        var frontOneHour = timestampToTime(timestamp);
        frontOneHour = Date.parse(frontOneHour) / 1000;
        var h = frontOneHour - timestamp;
        countdown(this, h * 1000);
    },
    /**
     * 分享当前页面
     */
    onShareAppMessage: function () {
        // 构建页面参数
        let params = app.globalData.urlEncode({
            item_id: this.item_id,
            referee_id: app.globalData.getUserId()
        });
        return {
            title: this.detail.name,
            desc: '',
            path: '/pages/goods/index?' + params
        };
    },
    methods: {
        /**
         * 获取商品信息
         */
        getGoodsDetail: function () {
            let that = this;
            app.globalData._get(
                'item/detail',
                {
                    item_id: that.item_id
                },
                function (result) {
                    // 初始化商品详情数据
                    let data = that.initGoodsDetailData(result.data);
                    that.setData(data);
                }
            );
        },

        /**
         * 初始化商品详情数据
         */
        initGoodsDetailData: function (data) {
            let that = this;
            // 富文本转码
            if (data.detail.goods_content.length > 0) {
                that.article_content = that.escape2Html(data.detail.goods_content);
            }

            // 商品价格/划线价/库存
            data.item_sku_id = data.detail.sku == [] ? 1 : data.detail.sku[0].key;
            var goods_price =
                data.detail.sku == []
                    ? data.detail.shop_price * (data.detail.discount ? data.detail.discount / 10 : 1)
                    : data.detail.sku[0].shop_price * (data.detail.discount ? data.detail.discount / 10 : 1);
            data.goods_price = goods_price.toFixed(2);
            data.stock_num = data.detail.sku == [] ? data.detail.store_count : data.detail.sku[0].store_count;
            // 初始化商品多规格

            if (data.detail.spec_type != 0) {
                data.specData = that.initManySpecData(data.detail.spec_rel);
            }
            return data;
        },

        /**
         * 初始化商品多规格
         */
        initManySpecData: function (data) {
            for (let i in data) {
                for (let j in data[i].spec_item) {
                    if (j < 1) {
                        data[i].spec_item[0].checked = true;
                        this.goods_spec_arr[i] = data[i].spec_item[0].id;
                    }
                }
            }
            return data;
        },

        /**
         * 点击切换不同规格
         */
        modelTap: function (e) {
            let attrIdx = e.currentTarget.dataset.attrIdx;
            let itemIdx = e.currentTarget.dataset.itemIdx;
            let specData = this.specData;
            for (let i in specData) {
                for (let j in specData[i].spec_item) {
                    if (attrIdx == i) {
                        specData[i].spec_item[j].checked = false;
                        if (itemIdx == j) {
                            specData[i].spec_item[itemIdx].checked = true;
                            this.goods_spec_arr[i] = specData[i].spec_item[itemIdx].id;
                        }
                    }
                }
            }
            this.setData({
                specData
            });
            // 更新商品规格信息
            this.updateSpecGoods();
        },

        /**
         * 更新商品规格信息
         */
        updateSpecGoods: function () {
            let spec_sku_id = this.goods_spec_arr.join('_');
            // 查找skuItem
            let spec_list = this.detail.sku;
            let skuItem = spec_list.find((val) => {
                return val.key == spec_sku_id;
            }); // 记录item_sku_id
            // 更新商品价格、划线价、库存
            if (typeof skuItem === 'object') {
                this.setData({
                    item_sku_id: skuItem.key,
                    goods_price: (skuItem.shop_price * this.detail.discount) / 10,
                    line_price: skuItem.price,
                    stock_num: skuItem.store_count
                });
            } else {
                this.setData({
                    stock_num: 0
                });
            }
        },

        /**
         * 设置轮播图当前指针 数字
         */
        setCurrent: function (e) {
            this.setData({
                currentIndex: e.detail.current + 1
            });
        },

        /**
         * 控制商品规格/数量的显示隐藏
         */
        onChangeShowState: function () {
            this.setData({
                showView: !this.showView
            });
        },

        /**
         * 返回顶部
         */
        goTop: function (t) {
            this.setData({
                scrollTop: 0
            });
        },

        /**
         * 显示/隐藏 返回顶部按钮
         */
        scroll: function (e) {
            this.setData({
                floorstatus: e.detail.scrollTop > 200
            });
        },

        /**
         * 增加商品数量
         */
        up: function () {
            this.setData({
                goods_num: ++this.goods_num
            });
        },

        /**
         * 减少商品数量
         */
        down: function () {
            if (this.goods_num > 1) {
                this.setData({
                    goods_num: --this.goods_num
                });
            }
        },

        /**
         * 跳转购物车页面
         */
        flowCart: function () {
            uni.switchTab({
                url: '../flow/index'
            });
        },

        /**
         * 加入购物车and立即购买
         */
        submit: function (e) {
            let that = this;
            let submitType = e.currentTarget.dataset.type;
            let prom = e.currentTarget.dataset.prom;
            let other = e.currentTarget.dataset.other;
            other ? other : (other = 0);
            prom ? prom : (prom = 0);
            if (submitType === 'buyNow') {
                // 立即购买
                uni.navigateTo({
                    url:
                        '../flow/checkout?' +
                        app.globalData.urlEncode({
                            order_type: 'buyNow',
                            item_id: that.item_id,
                            goods_num: that.goods_num,
                            item_sku_id: that.item_sku_id,
                            prom: prom,
                            other: other
                        })
                });
            } else if (submitType === 'addCart') {
                // 加入购物车
                app.globalData._post_form(
                    'cart/add',
                    {
                        item_id: that.item_id,
                        goods_num: that.goods_num,
                        item_sku_id: that.item_sku_id
                    },
                    function (result) {
                        app.globalData.showSuccess(result.msg);
                        that.setData(result.data);
                    }
                );
            }
        },

        /**
         * 浏览商品图片
         */
        previewImages: function (e) {
            let index = e.currentTarget.dataset.index;
            let imageUrls = [];
            this.detail.image.forEach(function (item) {
                imageUrls.push(item.file_path);
            });
            uni.previewImage({
                current: imageUrls[index],
                urls: imageUrls
            });
        },

        /**
         * 跳转到评论
         */
        navigateToComment: function () {
            uni.navigateTo({
                url: './comment/comment?item_id=' + this.item_id
            });
        },

        /**
         * 显示分享选项
         */
        openActionsheet(e) {
            // 记录formId
            app.globalData.saveFormId(e.detail.formId);
            this.setData({
                'share.show': true
            });
        },

        /**
         * 关闭分享选项
         */
        closeActionSheet() {
            this.setData({
                'share.show': false
            });
        },

        /**
         * 点击分享选项
         */
        clickAction(e) {
            if (e.detail.index === 0) {
                // 显示商品海报
                this.showPoster();
            }
            this.closeActionSheet();
        },

        /**
         * 切换商品海报
         */
        togglePopup() {
            this.setData({
                'share.showPopup': !this.share.showPopup
            });
        },

        /**
         * 显示商品海报图
         */
        showPoster: function () {
            let that = this;
            uni.showLoading({
                title: '加载中'
            });
            app.globalData._get(
                'goods/poster',
                {
                    item_id: that.item_id
                },
                function (result) {
                    that.setData(result.data, function () {
                        that.togglePopup();
                    });
                },
                null,
                function () {
                    uni.hideLoading();
                }
            );
        },

        /**
         * 保存海报图片
         */
        savePoster: function (e) {
            let that = this;
            // 记录formId
            app.globalData.saveFormId(e.detail.formId);
            uni.showLoading({
                title: '加载中'
            });
            // 下载海报图片
            uni.downloadFile({
                url: that.qrcode,
                success: function (res) {
                    uni.hideLoading();
                    // 图片保存到本地
                    uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function (data) {
                            uni.showToast({
                                title: '保存成功',
                                icon: 'success',
                                duration: 2000
                            });
                            // 关闭商品海报
                            that.togglePopup();
                        },
                        fail: function (err) {
                            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                                uni.showToast({
                                    title: '请允许访问相册后重试',
                                    icon: 'none',
                                    duration: 1000
                                });
                                setTimeout(function () {
                                    uni.openSetting();
                                }, 1000);
                            }
                        },
                        complete(res) {
                            console.log('complete');
                            // wx.hideLoading();
                        }
                    });
                }
            });
        },

        importFun() {
            console.log('占位：函数 import 未声明');
        },

        toOrder() {
            console.log('占位：函数 toOrder 未声明');
        }
    }
};
</script>
<style>
@import './index.css';
</style>
